import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;

public class MatchTag {

	HashMap<String,ArrayList<String>> patterns = new HashMap<String,ArrayList<String>>();
	ArrayList<String> out_str = new ArrayList<String>();
	
	public void readPattern(File file) throws IOException
	{
		BufferedReader sen = new BufferedReader(new FileReader(file));
		String tmp;
		while ((tmp = sen.readLine()) != null) {
			String[] field = tmp.split("\\s");
			if(patterns.containsKey(field[0]))
			{
				ArrayList<String> p = patterns.get(field[0]);
				p.add(field[1]);
				patterns.put(field[0], p);
			}
			else
			{
				ArrayList<String> p = new ArrayList<String>();
				p.add(field[1]);
				patterns.put(field[0], p);
			}
		}
	}
	
	public void match(File file) throws IOException
	{
		BufferedReader sen = new BufferedReader(new FileReader(file));
		String tmp;
		while ((tmp = sen.readLine()) != null) {
			String[] field = tmp.split("\\s");
			if(field.length != 2)
				continue;
			String output = tmp;
			Set<String> tags = patterns.keySet();
			for(String tag : tags)
			{
				ArrayList<String> pat = patterns.get(tag);
				boolean flag = false;
				for(String p : pat)
				{
					Pattern pa = Pattern.compile(p,Pattern.CASE_INSENSITIVE);
					Matcher matcher = pa.matcher(field[1]);
					if(matcher.find())
					{
						flag = true;
						break;
					}
				}
				if(flag)
					output = output+" "+tag;
			}
			out_str.add(output);
		}
	}
	
	public void write(File file) throws IOException
	{
		FileOutputStream fs = new FileOutputStream(file);
		OutputStreamWriter ow = new OutputStreamWriter(fs);
		BufferedWriter bw = new BufferedWriter(ow);
		for(String str : out_str)
		{
			bw.write(str);
			bw.newLine();
		}
		bw.close();
	}
	
	public static void main(String args[]) throws IOException
	{
		File pattern = new File("E:\\chenxj\\regularexpression\\src\\regex.txt");
		File test = new File("E:\\chenxj\\regularexpression\\src\\ctbtags.mrg");
		File res = new File("E:\\chenxj\\regularexpression\\src\\res.txt");
		MatchTag mat = new MatchTag();
		mat.readPattern(pattern);
		mat.match(test);
		mat.write(res);
		
		Pattern pa = Pattern.compile("^(\\-)?(0|[1-9]\\d*)(\\.\\d+)?$");
		Matcher matcher = pa.matcher("0.36");
		if(matcher.find())
		{
			//System.out.println("NUM");
		}
	}
}
